package com.woniu.controller;

import com.woniu.entity.User;
import com.woniu.entity.utils.ResponseEntity;
import com.woniu.service.AuthService;
import com.woniuxy.jwt.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    AuthService authService;
    @Resource
    RedisTemplate redisTemplate;
    @GetMapping("/login")
    public ResponseEntity login(User user){
        User dbUser =  authService.findUser(user);
        //比较登录的是否密码和数据库密码是否一致，我们暂时不用密码加密
        if (Objects.nonNull(dbUser)&&dbUser.getPassword().equals(user.getPassword())){
            //说明登录成功
            String token = JWTUtils.generateToken(user.getUsername());
            //正常这里就需要存储到redis中！！！还要开发一个刷新token！
            ResponseEntity success = new ResponseEntity(dbUser);
            success.put("token",token);
            //刷新token refreshToken
            String refreshToken = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(refreshToken,dbUser);
            //刷新token60min过期
            redisTemplate.expire(refreshToken,60, TimeUnit.MINUTES);
            success.put("refreshToken",refreshToken);
            return success;
        }else {
            return ResponseEntity.ERROR;
        }
    }
    @PutMapping("/")
    public ResponseEntity updateUser(@RequestBody User user){
        return new ResponseEntity(authService.updateUser(user));
    }
    @DeleteMapping("/clearCache")
    public ResponseEntity clearCache(){
        authService.clearCache();
        return new ResponseEntity("清除成功！");
    }
}
